# coding:utf-8
class Admin::MessageWarnningsController < AdminController
  set_tab :statistics
  set_tab :message_warnning, :sub_nav
  before_filter :setup, only: [:index]

  def index
    params[:message_warnning] ||= {}
    @message_warnnings = MessageWarnning.order('created_at DESC')
    @message_warnnings = @message_warnnings.where(mobile_number: params[:message_warnning][:mobile_number]) unless params[:message_warnning][:mobile_number].blank?
    @message_warnnings = @message_warnnings.by_warnning_code(params[:message_warnning][:warnning_code]) if params[:message_warnning][:warnning_code] and params[:message_warnning][:warnning_code] != 'all'
    @message_warnnings = @message_warnnings.before_date(params[:message_warnning][:end_date]) unless params[:message_warnning][:end_date].blank?
    @message_warnnings = @message_warnnings.after_date(params[:message_warnning][:start_date]) unless params[:message_warnning][:start_date].blank?
    
    respond_to do |format|
      format.html {
        if @message_warnnings.all.size > 0
          @chart_attrs = get_pie_chart_attrs(@message_warnnings)
        end
        @message_warnnings = @message_warnnings.page params[:page]
      }
      format.csv {   
        @message_warnnings = @message_warnnings.all
        send_data(csv_content_for(@message_warnnings),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "短信统计_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  private

  def setup
    @ways = ["统计","短信统计"]
    @left_panel = "layouts/statistics_left_panel"
  end

  def get_pie_chart_attrs(message_warnnings)
    chart_attrs = {:type => 'pie'}
    chart_attrs[:title] = "短信分布"
    chart_attrs[:name] = "短信分布"
    legends = Hash.new(0)
    message_warnnings.all.each do |message_warnning|
      legends[message_warnning.display_name] += 1
    end
    chart_attrs[:legends] = legends
    chart_attrs
  end

  def csv_content_for(objs)  
    CSV.generate do |csv|  
      csv << ["\xEF\xBB\xBF手机","代码", "信息", "创建时间"]  
      objs.each do |record|  
        csv << [    
          record.mobile_number,
          record.warnning_code,
          record.display_name,
          record.created_at.stamp("2013-03-12 22:01:01") 
        ]
      end
    end
  end

end
